<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->model('admin','',TRUE);
	}

	function index(){
		if($this->session->userdata('admin')){
			$session_data = $this->session->userdata('admin');
			$this->data['username'] = $session_data['username'];
			redirect('dashboard', 'refresh');
		}
		$this->load->view('login');
	}

	function verify(){
		//This method will have the credentials validation
		$this->load->library('form_validation');

		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

		if($this->form_validation->run() == FALSE){
			redirect('', 'refresh');
		}else{
			//Go to private area
			redirect('dashboard', 'refresh');
		}
	}

	function check_database($password){
		//Field validation succeeded.&nbsp; Validate against database
		$username = $this->input->post('username');
		//query the database
		$result = $this->admin->login($username, $password);

		if($result){
			$sess_array = array();
			foreach($result as $row){
				$sess_array = array('username' => $row->username_admin);
				$this->session->set_userdata('admin', $sess_array);
			}
			return TRUE;
		}else{
			$this->form_validation->set_message('check_database', 'Invalid username or password');
			return false;
		}
	}
	
	function logout(){
		$this->session->sess_destroy();
		redirect('', 'refresh');	
	}
}
?>
